package com.example.widget_lib.widget.progress.circle;

import com.example.widget_lib.ResourceTable;
import com.example.widget_lib.bean.CircleBean;
import com.example.widget_lib.utils.AttrUtils;
import com.example.widget_lib.utils.LogUtil;
import com.example.widget_lib.utils.PxUtil;
import com.example.widget_lib.utils.Util;
import com.example.widget_lib.widget.base.CircleCenterStyle;
import com.example.widget_lib.widget.ring.RingView;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.render.Arc;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Color;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.global.resource.solidxml.TypedAttribute;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 自定义分段圆环（内含图例）
 *
 * @author hongbing
 * @since 20181219
 */
public class CircleView extends ProgressBar implements Component.DrawTask {
    private static final String TAG = CircleView.class.getSimpleName();
    public final static int[] COLORS = {
            Color.rgb(88, 181, 250), // 蓝色
            Color.rgb(255, 196, 0), // 黄色
            Color.rgb(101, 226, 175),// 绿色
            Color.rgb(255, 105, 83), //红色
            Color.rgb(202, 129, 222), // 紫色
            Color.rgb(153, 153, 153), // 灰色
            Color.rgb(233, 255, 83) // 浅黄色
    };

    /**
     * 数据为空显示的文案
     */
    private static final String NOT_DATA = "暂无统计数据";
    // 圆环颜色集合
    private int[] circle_colors = COLORS;

    /**
     * 自定义属性
     */
    private CircleCenterStyle mCenterStyle; // 图形中间样式
    private int mRadius;
    private PixelMap mCenterBitmap;
    private String mCenterStr;
    private int mCenterTxtSize;
    private int mCenterTxtColor;
    private int mCenterTxtMargin;

    private Paint mPaint; // 圆环画笔
    private Paint mTxtPaint; // 文本画笔
    private int mBorderW; // 环的厚度
    private RectFloat mArcRectF;
    private int ordinal;
    private boolean isShow;

    public CircleView(Context context) {
        this(context, null);
    }

    public CircleView(Context context, AttrSet attrSet) {
        super(context, attrSet);
        initCustomAttrs(attrSet);
        init();
    }

    public CircleView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initCustomAttrs(attrSet);
        init();

    }

    private void initCustomAttrs(AttrSet attrs) {
        try {
            Resource resource = getResourceManager().getResource(ResourceTable.Media_widget_icon_person);
            mCenterBitmap = ImageSource.create(resource, new ImageSource.SourceOptions()).createPixelmap(null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mCenterStr = AttrUtils.getStringFromAttr(attrs, "circleView_cv_center_txt", "测试");
//                    mCenterTxtSize = (int)PxUtil.fp2px(map.get(key).getFloatValue());
        mCenterTxtSize = AttrUtils.getDimensionFromAttr(attrs, "circleView_cv_center_txt_size", (int) PxUtil.fp2px(12));
        LogUtil.loge("=======" + mCenterTxtSize);

//                    mCenterTxtColor = Color.getIntColor(map.get(key).getStringValue());
        mCenterTxtColor = AttrUtils.getColorFromAttr(attrs, "circleView_cv_center_txt_color", Color.getIntColor("#2A2A2A"));

//                    mCenterTxtMargin = PxUtil.fp2px(map.get(key).getFloatValue());
        mCenterTxtMargin = AttrUtils.getDimensionFromAttr(attrs, "circleView_cv_cengter_txt_margin", (int) PxUtil.vp2px(4));
//                    mBorderW = (int) PxUtil.vp2px(map.get(key).getIntegerValue());
        mBorderW = AttrUtils.getDimensionFromAttr(attrs, "circleView_cv_boderW", (int) PxUtil.vp2px(10));
//                    mRadius = (int) PxUtil.vp2px(map.get(key).getIntegerValue());
        mRadius = AttrUtils.getDimensionFromAttr(attrs, "circleView_cv_radius", (int) PxUtil.vp2px(16));
//                    ordinal = (int) PxUtil.vp2px(map.get(key).getIntegerValue());
        ordinal = AttrUtils.getIntegerFromAttr(attrs, "ordinal", 0);
        mCenterStyle = CircleCenterStyle.values()[ordinal];

    }

    private void init() {
//        setEstimateSizeListener(this::onEstimateSize);
        addDrawTask(this);
        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                /**
                 * 动态计算列数
                 */
                int expectSize = Math.min(getWidth(), getHeight());

                mRadius = (expectSize - getPaddingTop() - getPaddingBottom() - mBorderW) / 2;
                if (mArcRectF == null) {
                    mArcRectF = new RectFloat();
                }
                mArcRectF.fuse(0, 0, mRadius * 2, mRadius * 2);
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        });

        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE_STYLE);
        mPaint.setStrokeWidth(mBorderW);
        mPaint.setAntiAlias(true);

        mTxtPaint = new Paint();
        mTxtPaint.setStyle(Paint.Style.FILL_STYLE);
        mTxtPaint.setAntiAlias(true);
    }

    public void setBorderW(int borderW) {
        mBorderW = borderW;
        mPaint.setStrokeWidth(mBorderW);
    }

//    @Override
//    public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {
//
//        int expectSize = Math.min(getWidth(), getHeight());
//
////        LogUtil.logD("201810301418", "onMeasure-->expectSize = " + expectSize + "->width = " + width + "->height = " + height
////                + "->widthMeasureSpec = " + widthMeasureSpec + "->heightMeasureSpec = " + heightMeasureSpec);
//
//        mRadius = (expectSize - getPaddingTop() - getPaddingBottom() - mBorderW) / 2;
//        if (mArcRectF == null) {
//            mArcRectF = new RectFloat();
//        }
//        mArcRectF.fuse(0, 0, mRadius * 2, mRadius * 2);
//        return false;
//    }

    public int[] getCircleColos() {
        return circle_colors;
    }

//    public void setCircleColorsArr(int[] circle_colors) {
//        this.circle_colors = circle_colors;
//    }

    public void setCircleColors(int... circle_colors) {
        this.circle_colors = circle_colors;
    }

    public void setCenterTxtSize(int centerTxtSize) {
        mCenterTxtSize = centerTxtSize;
    }

    public void setCenterTxtColor(int centerTxtColor) {
        mCenterTxtColor = centerTxtColor;
    }

    public void setCenterStyle(CircleCenterStyle centerStyle) {
        mCenterStyle = centerStyle;
    }

    public void setEmpty() {
        setData(null);
    }

    private List<CircleBean> mList = new ArrayList<CircleBean>();

    public void setData(List<CircleBean> beans) {
        isShow = true;
        mList.clear();
        if (beans != null && beans.size() > 0) {
            mList.addAll(beans);
        }
        invalidate();
    }

    public void setCenterStr(String centerStr) {
        mCenterStr = centerStr;
    }

    public void setCenterStyle(int type) {
        mCenterStyle = CircleCenterStyle.values()[type];
    }

    private void drawEmptyData(Canvas canvas) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(new Color(Color.rgb(200, 200, 200)));
        paint.setTextSize((int) PxUtil.fp2px(12f));


        int canvasW = getWidth();
        int canvasH = getHeight();
        int[] wh = Util.getTextWH(NOT_DATA, paint);
        // 画文字的时候，y值是文字的底线
//        canvas.drawText(NOT_DATA, canvasW / 2 - wh[0] / 2, canvasH / 2 + wh[1] / 2 - ((int) PxUtil.vp2px(1.5f)), paint);
        canvas.drawText(paint, NOT_DATA, canvasW / 2 - wh[0] / 2, canvasH / 2 + wh[1] / 2 - PxUtil.vp2px(1.5f));
    }

    /**
     * 绘制环形中心视图
     *
     * @param canvas
     * @throws IllegalArgumentException 图形结合功能尚未实现
     */
    private void drawCenterView(Canvas canvas) {
        if (mCenterStyle == CircleCenterStyle.Icon) { // 绘制中间图标
            PixelMapHolder mapHolder = new PixelMapHolder(mCenterBitmap);
            canvas.drawPixelMapHolder(mapHolder, mRadius - mCenterBitmap.getImageInfo().size.width / 2, mRadius - mCenterBitmap.getImageInfo().size.height / 2, mPaint);
        } else if (mCenterStyle == CircleCenterStyle.Txt) { // 绘制中间文本
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setDither(true);
            paint.setTextSize(mCenterTxtSize);
//            paint.setColor(new Color(mCenterTxtColor));
            int[] wh = Util.getTextWH(mCenterStr, paint);
            canvas.drawText(paint, mCenterStr, mRadius - wh[0] / 2, mRadius + wh[1] / 2); // 字体开始绘制位置y的值是从字体底部(baseline)开始算的
        } else if (mCenterStyle == CircleCenterStyle.Double_Txt) { // 绘制中间文本，两行
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setDither(true);
            paint.setTextSize(mCenterTxtSize);
            //真机设置颜色后不显示字体
            paint.setColor(new Color(mCenterTxtColor));

            String[] centerTxt = mCenterStr.split(" ");
            if (centerTxt.length>1){
            int[] wh1 = Util.getTextWH(centerTxt[0], paint);
            int[] wh2 = Util.getTextWH(centerTxt[1], paint);

            LogUtil.loge("201812201446", "源文本 = " + mCenterStr + "->文本1 = " + centerTxt[0] + "->文本2 = " + centerTxt[1]);
            canvas.drawText(paint, centerTxt[0], mRadius - wh1[0] / 2, mRadius - mCenterTxtMargin); // 字体开始绘制位置y的值是从字体底部开始算的
            canvas.drawText(paint, centerTxt[1], mRadius - wh2[0] / 2, mRadius + wh2[1] + mCenterTxtMargin); // 字体开始绘制位置y的值是从字体底部开始算的
            }else {
                int[] wh = Util.getTextWH(mCenterStr, paint);
                canvas.drawText(paint, mCenterStr, mRadius - wh[0] / 2, mRadius + wh[1] / 2); // 字体开始绘制位置y的值是从字体底部(baseline)开始算的
            }
        } else {
            throw new IllegalArgumentException("图形结合功能尚未实现");
        }
    }

    /**
     * 绘制圆环
     *
     * @param canvas
     */
    private void drawCircleRing(Canvas canvas) {
        if (mList == null || mList.isEmpty()) {
            return;
        }

        // 1.移动画布保证居中对齐
        canvas.save();
        canvas.translate(getWidth() / 2 - mRadius - mBorderW / 2, getPaddingTop() + mBorderW / 2);

        // 2.绘制圆环中间view
        drawCenterView(canvas);

        // 3.逐一绘制圆环、横线、文案
        int size = mList.size();
        if (size > circle_colors.length) {
            size = circle_colors.length;
        }
        CircleBean bean;
        for (int i = 0; i < size; i++) {
            bean = mList.get(i);
            mPaint.setColor(new Color(circle_colors[i]));

            LogUtil.loge("201812191556", "角度：start = " + bean.getStartPro() + "->end = " + bean.getEndPro());
            Arc arc = new Arc(bean.getStartPro() * 360 / 100, bean.getEndPro() * 360 / 100, false);

            canvas.drawArc(mArcRectF, arc, mPaint);
        }
        canvas.restore();
    }

    private boolean mIsSHowDebug;

    public void setImagePic(int imagePicId) {
        
        try {
            Resource resource = getResourceManager().getResource(imagePicId);
            mCenterBitmap = ImageSource.create(resource, new ImageSource.SourceOptions()).createPixelmap(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (mList != null && mList.size() > 0) {
            drawCircleRing(canvas);
        } else {
            if (isShow){
                drawEmptyData(canvas);
            }
        }
    }

    @Override
    public void addDrawTask(DrawTask task) {
        super.addDrawTask(task);
        task.onDraw(this, mCanvasForTaskOverContent);
    }
}
